package com.nf.practice.exportExcel;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SfDataExportTest3 {

//    private final String dmsUrl = "http://172.16.10.5:31314/service";
private final String dmsUrl = "http://192.168.40.49:1688/service";

    @Test
    public void batchExport2() {

//        String fileName = "E:/SFDSJ/sffile.xlsx";
        String fileName = "E:/SFDSJ/SfFileV1.2.xlsx";
//
//        ExcelReader reader = ExcelUtil.getReader(new File("E:/SFDSJ/sffile.xlsx"));
//        List<List<Object>> read = reader.read(1);
        // 读取到的数据
        List<SfFile> list = EasyExcel.read(fileName)
                .head(SfFile.class)
                .sheet()
                .doReadSync();

        List<SfImplementCountData> dataList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            String appNo = list.get(i).getAppNo();
            String name = list.get(i).getName();
            String idNo = list.get(i).getIdNo();
            System.out.println(appNo);
            System.out.println(idNo);
            System.out.println(name);

            JSONObject ss01EntJson = null;
            try {
                ss01EntJson = dataExport(appNo, idNo, name);
                Map<String, Object> map = dataAnalysis(ss01EntJson);
                List<Map<String, Object>> implementCasesData = (List<Map<String, Object>>) map.get("implementCasesData");
                for (int j = 0; j < implementCasesData.size(); j++) {
                    Map<String, Object> finalMap = implementCasesData.get(j);
                    SfImplementCountData data = new SfImplementCountData();
                    data.setAppNo(appNo).setName(name).setIdNo(idNo).setType("公开模型")
                            .setN_ajlx((String) finalMap.get("n_ajlx"))
                            .setC_ah((String) finalMap.get("c_ah"))
                            .setC_ah_ys((String) finalMap.get("c_ah_ys"))
                            .setC_ah_hx((String) finalMap.get("c_ah_hx"))
                            .setN_ajbs((String) finalMap.get("n_ajbs"))
                            .setN_jbfy((String) finalMap.get("n_jbfy"))
                            .setN_jbfy_cj((String) finalMap.get("n_jbfy_cj"))
                            .setC_ssdy((String) finalMap.get("c_ssdy"))
                            .setD_larq((String) finalMap.get("d_larq"))
                            .setN_ajjzjd((String) finalMap.get("n_ajjzjd"))
                            .setN_laay((String) finalMap.get("n_laay"))
                            .setN_sqzxbdje((String) finalMap.get("n_sqzxbdje"))
                            .setD_jarq((String) finalMap.get("d_jarq"))
                            .setN_jaay((String) finalMap.get("n_jaay"))
                            .setN_jabdje((String) finalMap.get("n_jabdje"))
                            .setN_jabdje_gj((String) finalMap.get("n_jabdje_gj"))
                            .setN_sjdwje((String) finalMap.get("n_sjdwje"))
                            .setN_wzxje((String) finalMap.get("n_wzxje"))
                            .setN_jafs((String) finalMap.get("n_jafs"))
                            .setN_ssdw((String) finalMap.get("n_ssdw"))
                            .setC_gkws_id((String) finalMap.get("c_gkws_id"))
                            .setC_gkws_glah((String) finalMap.get("c_gkws_glah"))
                            .setC_gkws_dsr((String) finalMap.get("c_gkws_dsr"))
                            .setC_gkws_pjjg((String) finalMap.get("c_gkws_pjjg"))
                            .setDsrDatas((String) finalMap.get("c_dsrxx"));
                    dataList.add(data);
                }
                System.out.println(idNo + "-" + name + "处理完成!");

            } catch (Exception e) {
                System.out.println(idNo + "-" + name + "处理异常!");
            }


        }

        ExcelWriter writer = ExcelUtil.getWriter(new File("E:/SFDSJ/司法执行明细2.xlsx"));
        if(!CollectionUtils.isEmpty(dataList)){
            writer.setSheet(0).write(dataList);
            writer.flush();
        }

//        ExcelWriter writer = ExcelUtil.getWriter(new File("D:\\项目相关记录\\777.xlsx"));
//
//        ExcelReader reader = ExcelUtil.getReader(new File("D:\\项目相关记录\\rmps-线下信审\\20231127-ai外呼\\cfsdb(1).xls"));
//        List<SFData> dataList = new ArrayList<>();
//
//        List<List<Object>> read = reader.read(1);
//        read.forEach(item->{
//            JSONObject jsonObject = JSONObject.parseObject(item.get(3).toString());
//            try{
//                if(item.get(2).equals("SXBZXR")){
//                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("sxbzxr");
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        SFData object = jsonArray.getObject(i, SFData.class);
//                        object.setId_card(idCardChange(item.get(0).toString()))
//                                .setName(item.get(1).toString())
//                                .setApp_no(item.get(4).toString()).setType("失信");
//                        dataList.add(object);
//                    }
//                }else if(item.get(2).equals("XGBZXR")){
//                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("xgbzxr");
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        SFData object = jsonArray.getObject(i, SFData.class);
//                        object.setId_card(idCardChange(item.get(0).toString()))
//                                .setName(item.get(1).toString())
//                                .setApp_no(item.get(4).toString()).setType("限高");
//                        dataList.add(object);
//                    }
//                }
//                System.out.println(item.get(1) + "-" + item.get(2) + "处理完成!");
//            }catch (Exception e){
//                System.out.println(item.get(1) + "-" + item.get(2) + "异常数据!");
//            }
//        });
//
//        if(CollectionUtils.isNotEmpty(dataList)){
//            writer.setSheet(0).write(dataList);
//            writer.flush();
//        }
    }

    private Map<String, Object> dataAnalysis(JSONObject ss01EntJson) {
        Map<String, Object> map = new HashMap<>();
        JSONObject ss01EntData = null;
        if (null != ss01EntJson && !ss01EntJson.isEmpty()) {
            ss01EntData = ss01EntJson.getJSONObject("data");
        }
        if (null != ss01EntData && !ss01EntData.isEmpty()) {
            JSONObject res = ss01EntData.getJSONObject("data");
            if (null != res && !res.isEmpty()) {
                map.put("entoutData", "entoutData");
                getMapData(map,res,"implement");
            }
        }
        return map;
    }

    private void getMapData(Map<String, Object> map, JSONObject res, String key) {
        // civil
        JSONObject json = res.getJSONObject(key);
        if (null != json && !json.isEmpty()) {
            JSONArray cases= json.getJSONArray("cases");
            if (!CollectionUtils.isEmpty(cases)) {
                switch (key) {
                    case ("implement"):
                        map.put("implementCasesData",getCaseDetailData(cases,key));
                        break;
                }
            }

        }
    }

    private List<Map<String, Object>> getCaseDetailData(JSONArray originArr, String key) {
        List<Map<String, Object>> resData = new ArrayList<>();
        for (int i = 0; i < originArr.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            JSONObject json = originArr.getJSONObject(i);
            if (null != json && !json.isEmpty()) {
                switch (key) {
                    case ("implement"):
                        getImplementMap(map,json);
                        break;
                }
                resData.add(map);
            }
        }
        return resData;
    }

    private void getImplementMap(Map<String, Object> map, JSONObject json) {
        map.put("n_ajlx",json.getString("n_ajlx"));
        map.put("c_ah",json.getString("c_ah"));
        map.put("c_ah_ys",json.getString("c_ah_ys"));
        map.put("c_ah_hx",json.getString("c_ah_hx"));
        map.put("n_ajbs",json.getString("n_ajbs"));
        map.put("n_jbfy",json.getString("n_jbfy"));
        map.put("n_jbfy_cj",json.getString("n_jbfy_cj"));

        map.put("c_ssdy",json.getString("c_ssdy"));
        map.put("n_ajjzjd",json.getString("n_ajjzjd"));
        map.put("d_larq",json.getString("d_larq"));

        map.put("n_laay",json.getString("n_laay"));
        map.put("n_sqzxbdje",json.getString("n_sqzxbdje"));
        map.put("d_jarq",json.getString("d_jarq"));
        map.put("n_jaay",json.getString("n_jaay"));
        map.put("n_jabdje",json.getString("n_jabdje"));
        map.put("n_jabdje_gj",json.getString("n_jabdje_gj"));
        map.put("n_sjdwje",json.getString("n_sjdwje"));
        map.put("n_wzxje",json.getString("n_wzxje"));
        map.put("n_jafs",json.getString("n_jafs"));

        map.put("n_ssdw",json.getString("n_ssdw"));
        map.put("c_gkws_id",json.getString("c_gkws_id"));
        map.put("c_gkws_glah",json.getString("c_gkws_glah"));
        map.put("c_gkws_dsr",json.getString("c_gkws_dsr"));
        map.put("c_gkws_pjjg",json.getString("c_gkws_pjjg"));
        getDsrXx(map,json);
    }

    private void getDsrXx(Map<String, Object> map,JSONObject json) {
        JSONArray c_dsrxxArr = json.getJSONArray("c_dsrxx");
//        List<Map<String,Object>> c_dsrxxList = new ArrayList<>();
        List<String> c_dsrxxList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(c_dsrxxArr)) {
            for (int i = 0; i < c_dsrxxArr.size(); i++) {
                JSONObject c_dsrxx = c_dsrxxArr.getJSONObject(i);
                if (c_dsrxx != null && !c_dsrxx.isEmpty()) {
//                    Map<String,Object> c_dsrxxMap = new HashMap<>();
//                    c_dsrxxMap.put("c_mc",c_dsrxx.getString("c_mc"));
//                    c_dsrxxMap.put("n_dsrlx",c_dsrxx.getString("n_dsrlx"));
//                    c_dsrxxMap.put("n_ssdw",c_dsrxx.getString("n_ssdw"));
//                    c_dsrxxList.add(c_dsrxxMap);

                    String dsrXx = c_dsrxx.getString("c_mc") + "/"
                            + c_dsrxx.getString("n_dsrlx") + "/"
                            + c_dsrxx.getString("n_ssdw");
                    c_dsrxxList.add(dsrXx);
                }
            }
        }
        map.put("c_dsrxx",String.join(",", c_dsrxxList));
    }

    @Test
    public void batchExport(){
        String fileName = "E:/SFDSJ/sffile.xlsx";
        // 读取到的数据
        List<SxDataDetail> result = new ArrayList();
        List<SfFile> list = EasyExcel.read(fileName)
                .head(SfFile.class)
                .sheet()
                .doReadSync();
        Long begin = System.currentTimeMillis();
        for (int i = 0; i < list.size(); i++) {
            String appNo = list.get(i).getAppNo();
            String name = list.get(i).getName();
            String idNo = list.get(i).getIdNo();
            System.out.println(appNo);
            System.out.println(idNo);
            System.out.println(name);
//            List<SxDataDetail> l = dataExport(appNo, idNo, name);
//            result.addAll(dataExport(appNo, idNo, name));
        }

        System.out.println("=========个人失信Excel导出开始========");
//        String filePath = "E:/SFDSJ/" + name + idNo.replaceAll("(?<=\\w{6})\\w(?=\\w{4})", "*") + "失信.xlsx";
        String filePath = "E:/SFDSJ/result1.xlsx";
        EasyExcel.write(filePath, SxDataDetail.class).sheet(1).doWrite(result);
        System.out.println("=========个人失信Excel导出结束========");
        System.out.println("计算耗时：" + (System.currentTimeMillis() - begin) + "ms");
    }

//    @Test
    public JSONObject dataExport(String appNo,String idNo,String name) {
        Date date = new Date();
        LocalDateTime startDate = date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endDate = startDate.plusYears(5); // 在开始日期上加五年得到结束日期
        // 将日期转换为指定格式
        DateTimeFormatter authedFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = startDate.format(authedFormatter);
        String inquiredAuth = "authed:" + startDateStr + "-" + endDate.format(authedFormatter);

        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("app_no", appNo);
        reqMap.put("name", name);
        reqMap.put("id", idNo);
        reqMap.put("inquired_auth", inquiredAuth);
//        reqMap.put("phone", "");
        reqMap.put("cardId", idNo);
        reqMap.put("businessType", "offline");
        reqMap.put("systmeName", "手动");
        reqMap.put("businessScenario", "财务");

        // 2、调用dms
        // 2.1、公开模型
        JSONObject entoutJsonData = getSfData(reqMap,"ENTOUT");
        return entoutJsonData;
    }

    private JSONObject getSfData(Map<String,Object> reqMap,String model) {
        reqMap.put("model", model);
        String json = JSON.toJSONString(reqMap);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(dmsUrl + "/SS01");
        String resStr = null;
        try {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                resStr = EntityUtils.toString(res.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        JSONObject jsonData = new JSONObject();
        if (StringUtils.isNotBlank(resStr)) {
            jsonData = JSONObject.parseObject(resStr);
        }
        return jsonData;
    }

}
